from django.db.models import F, Case, When

from base.models import Goods
from purchase.api.utils import get_entry_stats
from store.models import GoodsStock

import logging

logger = logging.getLogger("django")


def get_stock_goods(goods_id, house_id, batch_num):
    """获取库存商品"""
    goods = GoodsStock.objects.filter(goods_id=goods_id, house_id=house_id, batch_num=batch_num).first()
    return goods


def create_goods_stock(obj):
    data = {
        "goods_id": obj.goods_id,
        "house_id": obj.entry.house_id,
        "batch_num": obj.batch_num,
        "specs": obj.goods.specs,
        "price": obj.price,
        "quantity": obj.nums
    }
    GoodsStock.objects.create(**data)


def update_stock_price(goods_id):
    entry = get_entry_stats(goods_id)
    avg_price = entry.get_avg_price()
    GoodsStock.objects.filter(goods_id=goods_id).update(price=avg_price)
    Goods.objects.filter(id=goods_id).update(purchase_price=avg_price)


def increase_goods_stock(obj):
    """增加库存"""
    goods = get_stock_goods(obj.goods_id, obj.entry.house_id, obj.batch_num)
    logger.info(goods)
    if not goods:
        create_goods_stock(obj)
    elif goods:
        ret = GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=obj.entry.house_id, batch_num=obj.batch_num). \
            update(quantity=F("quantity") + obj.nums)
        logger.info(ret)
        update_stock_price(obj.goods_id)


def decrease_goods_stocks(objs):
    """删减库存数量"""
    for obj in objs:
        decrease_goods_stock(obj)


def decrease_goods_stock(obj):
    """删减库存数量"""
    if obj.entry.flag == 0 or obj.entry.flag == 2 or obj.entry.flag == 3:
        logger.info("{}-{}-{}".format(obj.batch_num, obj.nums, obj.old_house_id if hasattr(obj, 'old_house_id') else obj.entry.house_id))

        ret = GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=obj.old_house_id if hasattr(obj, 'old_house_id') else obj.entry.house_id,
                                  batch_num=obj.batch_num)\
            .update(quantity=F("quantity") - obj.nums)
        logger.info(ret)
    elif obj.entry.flag == 1:
        stock = GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=obj.entry.house_id).first()
        stock.quantity = F('quantity') - obj.nums
        stock.save(update_fields=['quantity'])

    update_stock_price(obj.goods_id)


def sale_increase_goods_stocks(objs):
    """增加库存数量"""
    for obj in objs:
        sale_increase_goods_stock(obj)


def sale_increase_goods_stock(obj):
    """销售增加库存数量"""
    if obj.sale_order.flag == 0 or obj.sale_order.flag == 2 or obj.sale_order.flag == 3:
        house_id = obj.old_house_id if hasattr(obj, 'old_house_id') else obj.sale_order.house_id
        GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=house_id, batch_num=obj.batch_num)\
            .update(quantity=F("quantity") + obj.nums)
    elif obj.sale_order.flag == 1:
        house_id = obj.old_house_id if hasattr(obj, 'old_house_id') else obj.sale_order.house_id
        stock = GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=house_id).first()
        stock.quantity = F('quantity') + obj.nums
        stock.save(update_fields=['quantity'])


def sale_decrease_goods_stock(obj):
    """销售删减库存数量"""
    if obj.sale_order.flag == 0 or obj.sale_order.flag == 2 or obj.sale_order.flag == 3:

        GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=obj.sale_order.house_id,
                                  batch_num=obj.batch_num)\
            .update(quantity=F("quantity") - obj.nums)
    elif obj.sale_order.flag == 1:
        stock = GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=obj.sale_order.house_id).first()
        stock.quantity = F('quantity') - obj.nums
        stock.save(update_fields=['quantity'])


def store_decrease_goods_stocks(objs):
    """删减库存数量"""
    for obj in objs:
        store_decrease_goods_stock(obj)


def store_decrease_goods_stock(obj):
    """删减库存数量"""
    GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=obj.transfer.in_house_id, batch_num=obj.batch_num)\
        .update(quantity=F("quantity") - obj.nums)

    GoodsStock.objects.filter(goods_id=obj.goods_id, house_id=obj.transfer.out_house_id, batch_num=obj.batch_num) \
        .update(quantity=F("quantity") + obj.nums)

